﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;

namespace project_web2.AdminTool {
    public partial class AddandEditProduct : System.Web.UI.Page {

        DAL dal = new DAL();
        protected void Page_Load(object sender, EventArgs e) {
            if(!IsPostBack){
                if (Request.QueryString["id"] != null) {
                    string id = Request.QueryString["id"].ToString();
                    lbNote.Text = "Sửa Sản Phẩm " +id;

                    DataRow dr = getProductById(id);
                    txtName.Text = dr["productname"].ToString();
                    txtDescription.Text = dr["description"].ToString();
                    txtQuantity.Text = dr["quantity"].ToString();
                    txtUnit.Text = dr["unit"].ToString();
                    txtPrice.Text = dr["price"].ToString();
                    hideId.Value = dr["productid"].ToString();
                    hideImage.Value = dr["image"].ToString();
                    hideNew.Value = dr["isnew"].ToString();
                    bindCategory(dr["categoryid"].ToString(), getCatagries());
                    string sta = dr["status"].ToString();
                    if (sta == "True") {
                        chbStatus.Checked = true;
                    } else {
                        chbStatus.Checked = false;
                    }
                } else {
                    lbNote.Text = "Thêm Sản Phẩm!";
                    bindCategory("1", getCatagries());
                }
            }
        }
        private void bindCategory(string id, DataTable dt) {
            lbCategory.DataSource = dt;
            lbCategory.DataTextField = "categoryname";
            lbCategory.DataValueField = "categoryid";
            lbCategory.SelectedValue = id;
            lbCategory.DataBind();
        }
        private DataTable getCatagries() {
            string sql = "select categoryid, categoryname, description, parentid, status from Categories where status = 'True'";
            DataTable dt = dal.get_data(sql, false);
            return dt;
        }
        private DataRow getProductById(string id) {
            DataRow dr = null;
            string sql = "select * from Products where productid="+id;
            DataTable dt = dal.get_data(sql, false);
            if(dt.Rows.Count > 0){
                dr = dt.Rows[0];
            }
            return dr;
        }
        protected void btnExit_Click(object sender, EventArgs e) {
            Response.Redirect("ManagerProducts.aspx");
        }

        protected void btnSave_Click(object sender, EventArgs e) {
            string id = hideId.Value;
            string name = txtName.Text;
            string cateId = lbCategory.SelectedValue;
            string des = txtDescription.Text;
            string sta = "False";
            if(chbStatus.Checked){
                sta = "True";
            }
            string unit = txtUnit.Text;
            string quatity = txtQuantity.Text;
            string image = hideImage.Value;
            string price = txtPrice.Text;

            if(fuImage.HasFile){
                string path_tt = fuImage.PostedFile.FileName;
                string ten_tt = Path.GetFileName(path_tt);
                FileInfo kt_file = new FileInfo(Server.MapPath("../images/") + ten_tt);
                if (kt_file.Exists) {
                    Response.Write("<script>alert('Hình ảnh bị trùng tên, vui lòng sửa lại !');</script>");
                } else {
                    //Xoa file cũ neu edit
                    if (Request.QueryString["id"] != null) {
                        FileInfo thefile = new FileInfo(Server.MapPath("../images/") + image);
                        if (thefile.Exists) {
                            File.Delete(Server.MapPath("../images/") + image);
                        }
                    }
                    image = ten_tt;
                    fuImage.PostedFile.SaveAs(Server.MapPath("../images/") + image);
                }
            }

            if (Request.QueryString["id"] != null) {
                updateData(id, name, cateId, des, sta, unit, quatity, image, price);
            }else{
                insertData(name, cateId, des, sta, unit, quatity, image, price);
            }
        }
        private void updateData(string id, string name, string cateID, string des, string sta, string unit,
                 string quatity, string image, string price){
            string sql = "update Products set productname=N'" + name;
            sql += "', categoryid='" + cateID;
            sql += "', description=N'" + des;
            sql += "', status='" + sta;
            sql += "', unit='" + unit;
            sql += "', quantity='" + quatity;
            sql += "', image='" + image;
            sql += "', price='" + price;
            sql += "' where productid=" + id;

            dal.executeQuery(sql);
        }
        private void insertData(string name, string cateID, string des, string sta, string unit,
                                        string quatity, string image, string price) {
            string sql = "insert into  Products values(N'" + name;
            sql += "'," + cateID;
            sql += ",GETDATE(), GETDATE()";
            sql += ",N'" + des;
            sql += "','" + sta;
            sql += "','" + unit;
            sql += "'," + quatity;
            sql += ",N'" + image;
            sql += "', 1, 1, 1" ;
            sql += "," + price + ")";

            dal.executeQuery(sql);
        }
    }
}